/**
 *  ward @ 2019
 *  harrydeep@wardyan.top
 */
package top.wardyan.base.model;

import java.lang.reflect.Field;
import java.util.List;

import org.apache.log4j.Logger;

import com.jfinal.plugin.activerecord.Config;
import com.jfinal.plugin.activerecord.IBean;
import com.jfinal.plugin.activerecord.Model;

import top.wardyan.annotation.JFinalField;

/**
 * 基类:实体类
 * 通过注解的方式,实现属性
 * @author ward 2019年2月24日
 */
@SuppressWarnings("serial")
public class BaseModel<T extends BaseModel<T>> extends Model<T> implements IBean  {

	//protected Logger log = Logger.getLogger(this.getClass());
	/**
	@Override
	public boolean save() {
		/**
		JFinalModel modelAnnotation = this.getClass().getAnnotation(JFinalModel.class);
		Annotation[]  as = this.getClass().getAnnotations();
		System.out.println(modelAnnotation.field());
		System.out.println(modelAnnotation.type());
		//return super.save();
		 **//***
		List<Field>  list = Arrays.asList(this.getClass().getDeclaredFields());
        
        for(Field f : list) {
        	//
        	//f.isAnnotationPresent(JFinalModel.class);
        	JFinalField a = f.getAnnotation(JFinalField.class);
        	System.out.println(a.field());
        	System.out.println(a.type());
        }
		return true;
	}
	**/
	@Override
	public boolean save() {
		// 通过反射获取属性值的结果, 默认是没有出错
		Boolean rs = true;
		// 所有属性
		Field[] fields = this.getClass().getDeclaredFields();
		for(Field field : fields) {
			// 只有被注解的才处理
			if(field.isAnnotationPresent(JFinalField.class)) {
				JFinalField annotation = field.getAnnotation(JFinalField.class);
				try {
					this.set(annotation.field(), field.get(this));
				} catch (IllegalArgumentException | IllegalAccessException e) {
					//log.error(e);
					rs = false;
				}
			}
		}
		// 如果通过反射获取值出错, 则不保存并且返回失败; 如果通过反射取值没有问题, 则返回保存的结果
		return rs ? super.save() : rs;
	}
		@Override
		protected List<T> find(Config config, String sql, Object... paras) {
			List<T> rs = super.find(config, sql, paras);
			// Field[] fields = this.getClass().getDeclaredFields();
			for(T t : rs) {
				Field[] fields = t.getClass().getDeclaredFields();
				for(Field field : fields) {
					if(field.isAnnotationPresent(JFinalField.class)) {
						JFinalField annotation = field.getAnnotation(JFinalField.class);
						//annotation.field()
						try {
							field.set(this, this.get(annotation.field()));
						} catch (IllegalArgumentException | IllegalAccessException e) {
							//log.error(e);
						}
						
					}
				}
			}
			return rs;
		}
	
	
	
}
